#!/usr/bin/env bash

# Copyright (C) 2019-2025 jkadbear
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

RED='\033[1;31m'
GREEN='\033[1;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # No Color

UT_GITREPO="https://gitee.com/jkadbear/mytaste.git"
CONFIG_GITREPO="https://gitee.com/jkadbear/chief_config.git"
OHMYZSH_INSTALL_SCRIPT="https://gitee.com/mirrors/oh-my-zsh/raw/master/tools/install.sh"
HOMEBREW_INSTALL_SCRIPT="https://raw.githubusercontent.com/Homebrew/install/master/install"

# prompt successful message
echo_succ() {
    echo -e "${GREEN}*$1*${NC}"
}

# prompt failed message
echo_fail() {
    echo -e "${RED}*$1*${NC}"
}

# prompt info message
echo_info() {
    echo -e "${YELLOW}*$1*${NC}"
}

exist_cmd() {
    if type $1 >/dev/null 2>&1; then
        return 0
    else
        return 1
    fi
}

prompt_help() {
    echo
    echo "=============================================="
    echo "What do you want to do? (ENTER q to exit)"
    echo "1. copy ssh keys to another machine"
    echo "2. prepare *nix working environment"
    echo "3. back-up files"
    echo "4. update ut itself"
    echo "5. copy ssh keys to massive machines"
    echo -n "INPUT>> "
}

check_sshcopyid() {
    if [[ ! -e ~/.ssh/id_rsa && ! -e ~/.ssh/id_ed25519 ]]; then
        echo_info "No ssh key found."
        while true; do
            read -p "Auto-generate? [Y/n]" yn
            case $yn in
                "" | [Yy]* ) ssh-keygen -t rsa -P "";
                             break ;;
                [Nn]* ) echo_info "Try \`ssh-keygen -t rsa -P \"\"\`";
                        echo_info " or \`ssh-keygen -t rsa -b 4096 -C \"your-email\"\`";
                        exit 0 ;;
                * )     echo_info "Please answer y or n." ;;
            esac
        done
    fi
    if [[ "$OSTYPE" == "OSX" ]] && ! exist_cmd ssh-copy-id; then
        $INSTALL_PREFIX ssh-copy-id
    fi
}

# TODO error handle
run_sel() {
    case $1 in

    "1" )
        check_sshcopyid
        echo_info "Please input username(default: `whoami`):"
        read username
        username=${username:-`whoami`}
        echo_info "Please input port(default: 22):"
        read port
        port=${port:-22}
        echo_info "Please input remote-host-addr:"
        read remote_host
        echo_info "Please select the SSH public key file to use:"
        select key_file in ~/.ssh/id_rsa.pub ~/.ssh/id_ed25519.pub; do
            if [ -n "$key_file" ]; then
                break
            else
                echo_info "Invalid selection. Please choose 1 or 2."
            fi
        done
        echo_info "Executing: ssh-copy-id -i $key_file -p $port $username@$remote_host"
        ssh-copy-id -i "$key_file" -p "$port" "$username@$remote_host"
        ;;

    "2" )
        # install git
        if ! exist_cmd git; then
            echo_info "installing git..."
            $INSTALL_PREFIX git
        else
            echo_info "git already exists"
        fi
        # install vim
        if  ! exist_cmd vim; then
            echo_info "installing vim..."
            $INSTALL_PREFIX vim
        else
            echo_info "vim already exists"
        fi
        # install z-shell
        if  ! exist_cmd zsh; then
            echo_info "installing zsh..."
            $INSTALL_PREFIX zsh
        else
            echo_info "zsh already exists"
        fi
        # install oh-my-zsh
        if [[ ! -d ~/.oh-my-zsh ]]; then
            echo_info "installing oh-my-zsh..."
            wget $OHMYZSH_INSTALL_SCRIPT
            # do not enter zsh environment instantly
            # sed -i.bak '/env zsh/d' install.sh
            sh install.sh
            rm install.sh #install.sh.bak
        else
            echo_info "oh-my-zsh already exists"
        fi
        # install tmux
        if  ! exist_cmd tmux; then
            echo_info "installing tmux..."
            $INSTALL_PREFIX tmux
        else
            echo_info "tmux already exists"
        fi
        # apply configuration to zsh, vimperator, vim, tmux
        if [[ ! -d ~/.chief_config ]]; then
            cd ~
            git clone $CONFIG_GITREPO .chief_config
            cd .chief_config
            cp ./zshrc ~/.zshrc
            cp ./vimperatorrc ~/.vimperatorrc
            cp ./vimrc ~/.vimrc
            cp ./tmux.conf ~/.tmux.conf
            cp ./tmux.conf.local ~/.tmux.conf.local
            cd $OLDPWD
        else
            echo_info "~/.chief_config already exists"
            cd ~/.chief_config
            git pull
            cd $OLDPWD
        fi
        echo_succ "Successfully done"
        echo_info "Try 'chsh -s /bin/zsh' or 'sudo chsh username -s /bin/zsh'"
        echo_info "Then 'env zsh'"
        ;;

    "3" )
        if [[ ! -e ~/.mytaste/backup.sh ]]; then
            echo_fail "~/.mytaste/backup.sh does not exists!"
            return
        fi
        echo_info "[DEFAULT]: zsh ~/.mytaste/backup.sh (continue? [y/n])"
        read cho
        if [[ $cho == "y" || $cho == "Y" || $cho == "" ]]; then
            zsh ~/.mytaste/backup.sh
        fi
        ;;

    "4" )
        if [[ -d ~/.mytaste ]]; then
            cd ~/.mytaste
            echo_info "git pull"
            git pull
            cd $OLDPWD
        else
            git clone $UT_GITREPO ~/.mytaste
            cp ~/.mytaste/ut .
            echo_info "cloned git repo at '~/.mytaste'"
        fi
        echo_succ "Update done."
        echo_info "Please restart 'ut' and make sure that '~/.mytaste' is in your \$PATH."
        ;;

    "5" )
        check_sshcopyid
        echo_info "Please input username(default: `whoami`):"
        read username
        username=${username:-`whoami`}
        echo_info "Please input port(default: 22):"
        read port
        port=${port:-22}
        echo_info "Please input password:"
        read -s password

        if [[ $# -eq 1 ]]; then
            echo_info "Please input filename(containing hosts list):"
            read host_list
        else
            host_list=$2
        fi

        # host file not exists
        if [[ ! -e $host_list ]]; then
            echo_fail "no such file '$host_list'"
            return 1
        fi

        echo_info "Please select the SSH public key file to use:"
        select key_file in ~/.ssh/id_rsa.pub ~/.ssh/id_ed25519.pub; do
            if [[ -n "$key_file" && -f "$key_file" ]]; then
                break
            else
                echo_info "Invalid selection or file does not exist. Please try again."
            fi
        done

        while read remote_host; do
            [[ -z "$remote_host" ]] && continue
            echo_info "ssh-copy-id -i $key_file $username@$remote_host -p $port"
            ssh-copy-id -i "$key_file" -p "$port" "$username@$remote_host"
        done < "$host_list"
        ;;

    "q" )
        exit 0
        ;;

    * )
        echo_fail "Illegal input!"
        ;;

    esac
}

# detect OS type
if [[ $(uname) = "Darwin" ]]; then
    OSTYPE="OSX"
    if ! exist_cmd brew; then
        # install Homebrew
        /usr/bin/ruby -e "$(curl -fsSL $HOMEBREW_INSTALL_SCRIPT)"
    fi
    INSTALL_PREFIX="brew"
else
    #OSTYPE=$(cat /etc/issue | head -n 1 | cut -c1-6)
    OSTYPE=$(grep ^ID_LIKE= /etc/os-release | cut -d'=' -f2 | tr -d '"'  | cut -d' ' -f1)
    case $OSTYPE in
    "debian" )
        INSTALL_PREFIX="sudo apt-get install -y";;
    "Arch L" )
        INSTALL_PREFIX="sudo pacman -S --noconfirm";;
    "rhel" )
        INSTALL_PREFIX="sudo dnf install -y";;
    * )
        echo_fail "Unsupported OS Type!"
        exit 1;;
    esac
fi

if [[ $# > 0 ]]; then
    run_sel $1 $2
else
    while true; do
        prompt_help
        read sel
        run_sel $sel
    done
fi
